<?php
/**
 * Created by PhpStorm.
 * User: HarrisHuang
 * Date: 17/5/26
 * Time: 19:05
 */
namespace App\Http\Controllers;

use AliyunMNS\Client;
use AliyunMNS\Topic;
use AliyunMNS\Constants;
use AliyunMNS\Model\MailAttributes;
use AliyunMNS\Model\SmsAttributes;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\PublishMessageRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Log;
use App\Models\Users;

class UserController extends Controller
{

    /**
     * 注册绑定手机号
     *
     */
    public function register(Request $request, Users $users)
    {
        $name = $request->input('name');
        $mobile = $request->input('mobile');
        $code = $request->input('code');
        //$password = $request->input('password');
        if($name == '' || $mobile == '' || $code == ''){
            return $this->error();
        }
        //判断code是否成功
        $check = $this->checkCode($mobile, $code);
        if($check  == false){
            return $this->error('验证码错误');
        }
        //判断name和mobile是否已注册
        $res = $users->where('name', $name)->first();
        if($res){
            return $this->error('用户名已经注册');
        }
        $res = $users->where('mobile', $mobile)->first();
        if($res){
            return $this->error('手机号已经注册');
        }

        $users->name = $name;
        $users->mobile = $mobile;
        //$users->password = password_hash($password, PASSWORD_BCRYPT);
        $users->addTime = time();
        $users->save();
        $token = md5($mobile.time().'harris');
        Redis::set($token, 1);
        Redis::expire($token, 86400*30);
        return $this->success(['token' => $token]);
    }

    public function login(Request $request, Users $users)
    {
        $mobile = $request->input('mobile');
        //$password = $request->input('password');
        $code = $request->input('code');

        $check = $this->checkCode($mobile, $code);
        if($check  == false){
            return $this->error('验证码错误');
        }

        $info = $users->where('mobile', $mobile)->first();
        if(!$info){
            $users->mobile = $mobile;
            $users->addTime = time();
            $users->save();
        }
        /*
        if (!password_verify($password, $info['password'])) {
            return $this->error();
        }
        */
        $token = md5($mobile.time().'harris');
        Redis::set($token, 1);
        Redis::expire($token, 86400*30);
        return $this->success(['token' => $token]);
    }

    /**
     * 用户列表
     */

    public function lists(Request $request, Users $users)
    {
        $pageSize = $request->get('pageSize', 10);
        $list = $users::orderBy('id', 'desc')->paginate($pageSize);
        $list = $list->toArray();
        $res = [
            'total' => $list['total'],
            'data' => $list['data'],
        ];
        return $this->success($res);
    }



    /**
     * 验证code
     */
    public function checkCode($mobile, $code)
    {
        $info = Redis::get($mobile);
        if(!$info){
            return false;
        }
        if($code != $info){
            return false;
        }
        return true;
    }

    /**
     * 验证token
     */
    public function checkToken(Request $request)
    {
        $token = $request->get('token','');
        $info = Redis::get($token);
        if(!$info){
            return $this->error();
        }
        return $this->success();
    }


    /**
     * 发送验证码
     */
    public function sendCode(Request $request)
    {
        require base_path('lib/aliyunMns/mns-autoloader.php');
        $mobile = $request->get('mobile');
        $res = $this->run($mobile);
        if($res == false){
            return $this->error();
        }
        return $this->success();
    }

    public function run($mobile)
    {
        if ($mobile == '') {
            return false;
        }
        /**
         * Step 1. 初始化Client
         */
        $this->endPoint = "http://1662186353368647.mns.cn-hangzhou.aliyuncs.com/"; // eg. http://1234567890123456.mns.cn-shenzhen.aliyuncs.com
        $this->accessId = "LTAI1iMyrMwGz1ZF";
        $this->accessKey = "PgGJN36Ri25wzyBr59PClvvKebhmmt";
        $this->client = new Client($this->endPoint, $this->accessId, $this->accessKey);
        /**
         * Step 2. 获取主题引用
         */
        $topicName = "sms.topic-cn-hangzhou";
        $topic = $this->client->getTopicRef($topicName);
        /**
         * Step 3. 生成SMS消息属性
         */
        // 3.1 设置发送短信的签名（SMSSignName）和模板（SMSTemplateCode）
        $batchSmsAttributes = new BatchSmsAttributes("小铜人", "SMS_47010020");
        // 3.2 （如果在短信模板中定义了参数）指定短信模板中对应参数的值
        $code = rand(100000, 999999);
        Redis::set($mobile, $code);
        Redis::expire($mobile, 600);
        $batchSmsAttributes->addReceiver((string)$mobile, ["code" => (string)$code, "product" => "有米贷"]);
        //$batchSmsAttributes->addReceiver("YourReceiverPhoneNumber2", array("YourSMSTemplateParamKey1" => "value1"));
        $messageAttributes = new MessageAttributes([$batchSmsAttributes]);
        /**
         * Step 4. 设置SMS消息体（必须）
         *
         * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
         */
        $messageBody = "smsmessage";
        /**
         * Step 5. 发布SMS消息
         */
        $request = new PublishMessageRequest($messageBody, $messageAttributes);
        try {
            $res = $topic->publishMessage($request);
            if ($res->isSucceed() == 1) {
                return true;
            }
            return false;
        } catch (MnsException $e) {
            Log::error('发送短信失败,mobile' . $mobile . 'error=' . $e);
            return false;
        }
    }

}